import BaseLayout from '@/layouts/BaseLayout.vue'
import store from '@/store'

// 自动生成routers
const pageModules = import.meta.glob('../views/**/page.js', {
  eager: true,
  import: 'default',
})
// 引入导出模块
const compModules = import.meta.glob('../views/**/index.vue')
const routeList = Object.entries(pageModules).map(([pagePath, config]) => {
  const path = pagePath.replace('../views', '').replace('/page.js', '')
  const name = path.split('/').filter(Boolean).join('-')
  const compPath = pagePath.replace('page.js', 'index.vue')
  return {
    path: path,
    name: name,
    meta: config,
    component: compModules[compPath] || BaseLayout,
  }
})
// 拼成菜单树
function arrayToTree(list) {
  const result = [] // 用于存放结果
  const map = {} // 用于存放 list 下的节点
  // 遍历 list
  for (const item of list) {
    // 1. 获取节点的 id 和 父 id
    const { name } = item // ES6 解构赋值
    const id = name
    const parent_id = name.substring(0, name.lastIndexOf('-'))
    // console.log(parent_id, 999)
    // 2. 将节点存入 map
    if (!map[id]) map[id] = {}
    // 3. 根据 id，将节点与之前存入的子节点合并
    map[id] = map[id].children
      ? { ...item, children: map[id].children }
      : { ...item }
    // 4. 如果是根节点，存入 result
    if (name.split('-').length === 1) {
      result.push(map[id])
    } else {
      // 5. 反之，存入父节点
      if (!map[parent_id]) map[parent_id] = {}
      if (!map[parent_id].children) map[parent_id].children = []
      map[parent_id].children.push(map[id])
    }
  }
  // 将结果返回
  return result
}
// 定义路由重定向
function setRouteRedirect(data) {
  data.forEach((e) => {
    findLastItem(e, e.children?.[0] || {})
  })
  function findLastItem(parent, node) {
    if (node.children && node.children.length) {
      findLastItem(parent, node.children[0])
    } else {
      parent.redirect = node.path
      return
    }
  }
}

const routes = arrayToTree(routeList)
// 是否显示在菜单
const menuList = routes.filter((e) => e.meta.show !== false)
// 菜单排序
function sortTreeData(arr) {
  arr.sort((a, b) => {
    a.meta.transitionName = 'slide-right'
    return a.meta.sort - b.meta.sort
  })
  arr.forEach((item) => {
    if (item.children) {
      item.children = sortTreeData(item.children)
    }
  })
  return arr
}
sortTreeData(menuList)
setRouteRedirect(menuList)
store.dispatch('menus/setMenuList', menuList)
export default routes
